package cn.conac.rc.solr.common.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.SuggesterResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;

import cn.conac.rc.framework.utils.StringUtils;
import cn.conac.rc.solr.entity.IndexEntity;
import cn.conac.rc.solr.entity.ResultEntity;
import cn.conac.rc.solr.entity.SearchCondEntity;

;

public class SearchUtils {
	
	/**
	 * 更新索引
	 * @param indexEntity 索引相关数据
     * @param cloudSolrClient     solr云客户端
	 * @return  ret (0: 正常  -1：异常)
	 */ 
	public static int updateIndexByIdInfo(IndexEntity indexEntity, CloudSolrClient cloudSolrClient) {
		int ret = 0;
		try {
			// 先根据ID进行删除
			deleteIndexByIdInfo(indexEntity,cloudSolrClient);
			// 然后再增加索引
			saveIndex(indexEntity,cloudSolrClient);
		} catch (Exception e) {
			e.printStackTrace();
			ret = -1;
		}
		return ret;
	}

	/**
	 * 根据ID删除指定仓库的索引
	 * @param indexEntity 索引相关数据
     * @param cloudSolrClient     solr云客户端
	 * @return  ret (0: 正常  -1：异常)
	 */ 
	public static int deleteIndexByIdInfo(IndexEntity indexEntity, CloudSolrClient cloudSolrClient) {
		int ret =0;
		try {
			if(StringUtils.isNotEmpty(indexEntity.getId())){
				cloudSolrClient.deleteById(indexEntity.getCollectionName(), indexEntity.getId());
			}else{
				cloudSolrClient.deleteById(indexEntity.getCollectionName(), indexEntity.getIds());
			}
			cloudSolrClient.commit(indexEntity.getCollectionName());
		} catch (SolrServerException e) {
			e.printStackTrace();
			ret = -1;
		} catch (IOException e) {
			e.printStackTrace();
			ret = -1;
		}
		return ret;
	}
	
	/**
	 * 根据指定条件删除指定仓库的索引
	 * @param indexEntity 索引相关数据
     * @param cloudSolrClient     solr云客户端
	 * @return  ret (0: 正常  -1：异常 )
	 */ 
	public static int deleteIndexByCondition(IndexEntity indexEntity, CloudSolrClient cloudSolrClient) {
		int ret =0;
		try {
			cloudSolrClient.deleteByQuery(indexEntity.getCollectionName(), indexEntity.getDelCondtion());
			cloudSolrClient.commit(indexEntity.getCollectionName());
		} catch (SolrServerException e) {
			e.printStackTrace();
			ret = -1;
		} catch (IOException e) {
			e.printStackTrace();
			ret = -1;
		}
		return ret;
	}
	
	/**
	 * 保存索引
	 * @param indexEntity 索引相关数据
     * @param cloudSolrClient     solr云客户端
	 * @return  ret (0: 正常  -1：异常  -2 : 无索引数据)
	 */ 
	public static int saveIndex(IndexEntity indexEntity, CloudSolrClient cloudSolrClient) {
		int ret = 0;
		try {
			List<Map<String,Object>> indexData = indexEntity.getIndexData();
			if(indexData != null && indexData.size() > 0){
				List<SolrInputDocument> documentList = new ArrayList<SolrInputDocument>();
				SolrInputDocument doc = null;
				for(Map<String,Object> map : indexData){
					doc = new SolrInputDocument();
					Set<String> set = map.keySet();
					Iterator<String> iter = set.iterator();
					while(iter.hasNext()){
						String key = iter.next();
						Object value = map.get(key);
						doc.addField(key, value);
					}
					documentList.add(doc);
				}
				cloudSolrClient.add(indexEntity.getCollectionName(), documentList);
				cloudSolrClient.optimize(indexEntity.getCollectionName());
				cloudSolrClient.commit(indexEntity.getCollectionName());
				
			}else{
				ret = -2;
			}
		} catch (SolrServerException e) {
			e.printStackTrace();
			ret = -1;
		} catch (IOException e) {
			ret = -1;
		}
		return ret;
	}
	
	/**
	 *  solr通用查询（使用RequestHandler - >suggest ）
     * @param SearchCondEntity 检索相关条件
     * @param cloudSolrClient     solr云客户端
	 * @return 返回solr端查询所得结果(将结果保存到ResultEntity中)
	 */ 
	public static ResultEntity doCommQuery(SearchCondEntity searchCondEntity,CloudSolrClient cloudSolrClient) {
		ResultEntity result = new ResultEntity();
		try {
			
			// 设置关键字查询
			String queryWord = searchCondEntity.getQueryWord();
			if(StringUtils.isEmpty(queryWord)){
				return result;
			}
			//String escapeKeyWord = StrUtils.escapeQueryChars(queryWord);
			String escapeKeyWord = queryWord;
			
			// 将AND两边的空格再替换回来
			if(escapeKeyWord.indexOf("#AND#") != -1) {
				escapeKeyWord = escapeKeyWord.replaceAll("#AND#", " AND ");
			}
			
			if(escapeKeyWord.matches("[A-Za-z]{1}")){
				// 单个字母的场合转成小写字母（因为solr中使用一个大写的字母去检索查不到结果小写可以）
				escapeKeyWord = escapeKeyWord.toLowerCase();
			}
			
			List<String> assignmentFields = searchCondEntity.getAssignmentFields();
			List<Map<String,String>> assignFields = searchCondEntity.getAssignFields();
			String queryString = "";
			if (assignmentFields != null && assignmentFields.size() > 0) {
				for(String assignmentField : assignmentFields){
					queryString += assignmentField+":"+escapeKeyWord+" OR ";
				}
				int pos = queryString.lastIndexOf(" OR ");
				queryString = queryString.substring(0, pos);
			} else if (assignFields != null && assignFields.size() > 0) {
				String lastValue = "";
				for(Map<String,String> assignField : assignFields){
					Set<String> set = assignField.keySet();
					Iterator<String> iter = set.iterator();
					while(iter.hasNext()){
						String key = iter.next();
						String value = assignField.get(key);
						queryString += key + ":" + escapeKeyWord + " " + value + " ";
						lastValue = value;
					}
				}
				int pos = queryString.lastIndexOf(" "+lastValue+" ");
				queryString = queryString.substring(0, pos);
			} else {
				queryString = escapeKeyWord;
			}
			
//			System.out.println("queryString:"+queryString);
			SolrQuery solrQuery = new SolrQuery();
			solrQuery.setQuery(queryString);
			
			
			//设置显示域 
			String[] viewFields = searchCondEntity.getViewFields();
			if(null != viewFields && viewFields.length > 0){
				solrQuery.setFields(viewFields);
			}
			
			//设置高亮参数
			boolean isHighlight = searchCondEntity.getIsHighlight();
			List<String> highlightFields = searchCondEntity.getHighlightFields();
			if(isHighlight && highlightFields != null && highlightFields.size() > 0){
				// 开启高亮显示设置功能
				solrQuery.setHighlight(true);
				// 渲染高亮显示效果
				solrQuery.setHighlightSimplePre(searchCondEntity.getPreHighlight());
				solrQuery.setHighlightSimplePost(searchCondEntity.getPostHighlight());
//				solrQuery.setHighlightFragsize(searchCondEntity.getViewNums());
				// 设置要高亮显示的字段
				for(String highlightField: highlightFields){
					solrQuery.addHighlightField(highlightField);
				}
				solrQuery.setHighlightRequireFieldMatch(searchCondEntity.getHlRequireFieldMatch());
			}
			
			//设置过滤域
			Map<String,String> filterField = searchCondEntity.getFilterField();
			if(filterField != null && filterField.size() > 0){
				Set<String> set = filterField.keySet();
				Iterator<String> iter = set.iterator();
				while(iter.hasNext()){
					String key = iter.next();
					String value = filterField.get(key);
					solrQuery.addFilterQuery(key +":" +value);
				}
			}
			
			//排序域 String:需要排序的域名，Boolean：true 升序 false 降序
			Map<String,Boolean> sortField = searchCondEntity.getSortField();
			if (sortField != null) {
				Set<String> set = sortField.keySet();
				Iterator<String> iter = set.iterator();
				while(iter.hasNext()) {
					String key = iter.next();
					Boolean value = sortField.get(key);
					if(value){
						solrQuery.addSort(key,ORDER.asc);
					}else{
						solrQuery.addSort(key,ORDER.desc);
					}
				}
			}

			//开始行
			solrQuery.setStart(searchCondEntity.getStartNum());
			//一页显示多少行
			solrQuery.setRows(searchCondEntity.getPageCount());
			// 设置返回数据的格式
			solrQuery.set("wt","json");
			
			QueryResponse response = cloudSolrClient.query(searchCondEntity.getCollectionName() ,solrQuery);
			
			SolrDocumentList list = response.getResults();
			SolrDocument document = new SolrDocument();
			
			result.setNumFound(list.getNumFound());
			//高亮结果
			if (isHighlight && highlightFields != null && highlightFields.size() > 0) {
				Map<String,Map<String,List<String>>> map = response.getHighlighting();
				for(int i=0; i < list.size(); i++){
					for(int j=0; j< highlightFields.size(); j++){
						document = list.get(i);
						if(map != null && map.get(document.getFieldValue("id")) != null && map.get(document.getFieldValue("id")).get(highlightFields.get(j)) != null){
							document.setField(highlightFields.get(j), map.get(document.getFieldValue("id")).get(highlightFields.get(j)).get(0));
						}else{
							document.setField(highlightFields.get(j), document.getFieldValue(highlightFields.get(j)));
						}
					}
				}
				result.setSearchedResult(list);
			} else {
				result.setSearchedResult(list);
		   }
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 *  solr提示词查询（使用RequestHandler - >suggest ）
     * @param SearchCondEntity 检索相关条件
     * @param cloudSolrClient     solr云客户端
	 * @return 返回solr端查询所得重后的提示词List
	 */ 
	public static List<String> doSuggestQuery(SearchCondEntity searchCondEntity,CloudSolrClient cloudSolrClient) {
		List<String>  resultList = null;
		List<String> remDupedResultList = new ArrayList<String>();
		try {
			// 设置关键字查询
			String queryWord = searchCondEntity.getQueryWord();
			if(StringUtils.isEmpty(queryWord)){
				return remDupedResultList;
			}
	
			SolrQuery solrQuery = new SolrQuery();
			solrQuery.setQuery(queryWord);
			solrQuery.setRequestHandler("/suggest");
			
			// 设置返回数据的格式
			solrQuery.set("wt","json");
			
			QueryResponse response = cloudSolrClient.query(searchCondEntity.getCollectionName() ,solrQuery);
			SuggesterResponse suggesterResponse = response.getSuggesterResponse();
			resultList = suggesterResponse.getSuggestedTerms().get("mySuggester");
			remDupedResultList = StrUtils.remDupliStrList(resultList);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return remDupedResultList;
	}
}
